.valid.pixel.format <- c("UBIT1", "UBIT4", "BIT8", "UBIT8", "BIT16",
                         "UBIT16", "BIT32", "UBIT32", "BIT64", "SINGLE", "DOUBLE")

PrintPixelFormat <- function(){
  print(.valid.pixel.format)
}

.is.valid.pixel.format <- function(name){
  if (is.null(name)) {
    stop("name must be valid")
  }
  if (!is.character(name)) {
    stop("name must be character")
  }
  if (length(.valid.pixel.format[(.valid.pixel.format == toupper(name))]) == 1) {
    return(TRUE)
  } else {
    warning("pixel format is invalid")
    return(FALSE)
  }
}

Raster2Sp <- function(dataset){
  if(is.null(dataset)){
    stop("dataset must be valid")
  }
  
  if(class(dataset) != "DatasetRaster"){
    stop("dataset must be dataset raster")
  }
  
  if (!.IsDatasetTypeValid(GetDatasetType(dataset))) {
    stop()
  }
  
  xyPixs <- .iCall("R_DatasetRaster_Read_Pixels", dataset@pointer, PACKAGE="RSuperMap")
  
  if(is.null(xyPixs) || is.logical(xyPixs)) {
    warning("Reads dataset raster pixels failed")
    return(FALSE)
  } else {
    xs <- xyPixs[[1]]
    ys <- xyPixs[[2]]
    vs <- xyPixs[[3]]
    sp.spatialpoints <- SpatialPoints(cbind(xs, ys))
    data <- data.frame(vs)
    return(SpatialPixelsDataFrame(sp.spatialpoints, data = data))
  }
}

Sp2Raster <- function(pixel.df, ds, name, pixel.Format) {
  if(is.null(pixel.df) || !is(pixel.df, "SpatialPixelsDataFrame")){
    stop("pixel.df must be SpatialPixelsDataFrame object")
  }
  
  if(is.null(ds) || !is(ds, "Datasource")){
    stop("ds must be Datasource object")
  }
  
  if(is.null(name) || !is.character(name)){
    stop("name must be valid dataset name")
  }
  
  if(!.is.valid.pixel.format(pixel.Format)){
    stop()
  }
  
  bbox <- pixel.df@bbox
  rc <- c(bbox[1,1], bbox[2,2],bbox[1,2],bbox[2,1])
  grid <- pixel.df@grid
  width <- as.integer(grid@cells.dim[1])
  height <- as.integer(grid@cells.dim[2])
  values <- pixel.df@data[,1]
  gridIndex <- pixel.df@grid.index
  
  res <- .iCall("R_DatasetRaster_Writer_pixelDataFrame", ds@pointer, name, rc, 
                width, height, pixel.Format, gridIndex, values, PACKAGE="RSuperMap")
 
  if (is.null(res) || is.logical(res)) {
    warning("Writes SpatialPixelsDataFrame to dataset failed")
    return(FALSE)
  } else {
    dtName = GetDatasetName(res)
    ds@datasets[dtName] <- list(res)
    alias <- GetAlias(ds)
    .SetDatasource(alias, ds)
    return(list(ds, res))
  }
}